package models

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/sansaniot/ssiot-core/httpmvc/model"
	"gorm.io/datatypes"
)

type SysUserExt struct {
	Username string         `gorm:"primaryKey;type:varchar(255);comment:用户名"`
	Data     datatypes.JSON `gorm:"type:jsonb;comment:扩展数据"`
	model.Model
}

func (e *SysUserExt) TableName() string {
	return "sys_user_ext"
}

// 根据用户名查询扩展信息
func (e *SysUserExt) FindByUsername(username string) error {
	return e.Orm.Where("username = ?", username).First(e).Error
}

// 其他基础方法保持与现有模型一致
func (e *SysUserExt) Create() error {
	return e.Orm.Create(e).Error
}

func (e *SysUserExt) Update() error {
	return e.Orm.Model(e).Where("username = ?", e.Username).Updates(e).Error
}

func (e *SysUserExt) Delete() error {
	return e.Orm.Where("username = ?", e.Username).Delete(e).Error
}

// ... 其他现有方法 ...

func (e *SysUserExt) GetTagTotal(username string, tagName string) (int, error) {
	// 查询用户扩展数据
	if err := e.FindByUsername(username); err != nil {
		return 0, err
	}

	// 解析JSON数据
	var dataMap map[string]interface{}
	if err := json.Unmarshal(e.Data, &dataMap); err != nil {
		return 0, fmt.Errorf("JSON解析失败: %v", err)
	}

	// 层级获取数据
	tagData, ok := dataMap["tag"].(map[string]interface{})
	if !ok {
		return 0, errors.New("无效的标签数据结构")
	}

	targetTag, ok := tagData[tagName].(map[string]interface{})
	if !ok {
		return 0, fmt.Errorf("标签[%s]不存在", tagName)
	}

	total, ok := targetTag["total"].(float64)
	if !ok {
		return 0, fmt.Errorf("无效的total字段类型")
	}

	return int(total), nil
}
